﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Tenants.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;

namespace mozhi.smarterp.Finance.Tenants.EventHandler
{
    public class TenantConnectionCreateEventHandler : IDistributedEventHandler<TenantConnectionCreateEvent>,
        ITransientDependency
    {
        private IConfiguration _configuration;
        private readonly ICurrentTenant _currentTenant;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IDataSeeder _dataSeeder;
        private readonly ITenantStore _tenantStore;
        private IServiceProvider _serviceProvider;
        public TenantConnectionCreateEventHandler(IConfiguration configuration,ICurrentTenant currentTenant,
            IUnitOfWorkManager unitOfWorkManager,IDataSeeder dataSeeder,ITenantStore tenantStore, IServiceProvider serviceProvider)
        {
            _configuration = configuration;
            _currentTenant = currentTenant;
            _unitOfWorkManager = unitOfWorkManager;
            _dataSeeder = dataSeeder;
            _tenantStore = tenantStore;
            _serviceProvider = serviceProvider;
        }

        public async Task HandleEventAsync(TenantConnectionCreateEvent eventData)
        {
            var connectionString = _configuration.GetConnectionString(eventData.ConnectionStringName);

            if (connectionString.IsNullOrEmpty() || eventData.ConnectionString.IsNullOrEmpty())
                return;

            try
            {
                var tenantId = eventData.TenantId;

                using (_currentTenant.Change(tenantId))
                {
                    // Seed data
                    using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
                    {
                        var tenantConfiguration = await _tenantStore.FindAsync(tenantId);

                        var connectionStrings = tenantConfiguration?.ConnectionStrings;

                        if (connectionStrings != null && connectionStrings.Keys.Contains(eventData.ConnectionStringName)
                            && connectionStrings[eventData.ConnectionStringName] == eventData.ConnectionString)
                        {
                            var dbContext = await _serviceProvider.GetRequiredService<IDbContextProvider<FinanceDbContext>>().GetDbContextAsync();

                            var databaseExist = await dbContext
                                .Database.CanConnectAsync();

                            if (databaseExist)
                            {
                                await _dataSeeder.SeedAsync(new DataSeedContext(tenantId));
                            }

                        }
                        await uow.CompleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }
    }
}
